const gulp = require('gulp');
const connect = require('gulp-connect');
const postcss = require('gulp-postcss');
const autoprefixer = require('autoprefixer');
const sourcemaps = require('gulp-sourcemaps');
const customMedia = require('postcss-custom-media');
const cssVariables = require('postcss-css-variables');
const nesting = require('postcss-nesting');
const atImport = require('postcss-import');
const mediaVariables = require('postcss-media-variables');
const colorFunction = require('postcss-color-function');
const colorGray = require('postcss-color-gray');
const customSelectors = require('postcss-custom-selectors');
const ms = require('postcss-modular-scale');

gulp.task('connect', function () {
  connect.server({
    root: './',
    port: '1881',
    livereload: true
  });
});

gulp.task('reload', function () {
  gulp.src(['./**/*.html']).pipe(connect.reload());
});

gulp.task('watch', function () {
  gulp.watch('{.,elements,components}/*.html', ['reload']);
  gulp.watch('./postcss/**/*.css', ['postcss']);
});

gulp.task('postcss', function (...plugins) {
  return function () {
    gulp.src('./postcss/{main,demo}.css')
      .pipe(sourcemaps.init())
      .pipe(postcss(plugins))
      .pipe(sourcemaps.write('.'))
      .pipe(gulp.dest('./css/'))
      .pipe(connect.reload());
  };
}(
  atImport(), nesting(), ms(), cssVariables(), customMedia(), colorFunction(),
  colorGray(), autoprefixer(), customSelectors()
));


gulp.task('default', ['postcss', 'connect', 'watch']);
